package com.zhuozhou.jdyc.main.main.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import androidx.databinding.adapters.AbsListViewBindingAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhuozhou.jdyc.R;
import com.zhuozhou.jdyc.api.AppManager;
import com.zhuozhou.jdyc.api.ConstantsHelper;
import com.zhuozhou.jdyc.api.UserAccountHelper;
import com.zhuozhou.jdyc.base.BaseFragment;
import com.zhuozhou.jdyc.bean.BannerBean;
import com.zhuozhou.jdyc.databinding.IndexBinding;
import com.zhuozhou.jdyc.main.base.activity.PermissionsActivity;
import com.zhuozhou.jdyc.main.goods.activity.GoodsActivity;
import com.zhuozhou.jdyc.main.goods.activity.GoodsDetailActivity;
import com.zhuozhou.jdyc.main.main.activity.ClassifyActivity;
import com.zhuozhou.jdyc.main.main.activity.GoodsClassifyActivity;
import com.zhuozhou.jdyc.main.main.activity.MainActivity;
import com.zhuozhou.jdyc.main.main.activity.MerchantActivity;
import com.zhuozhou.jdyc.main.main.activity.SearchActivity;
import com.zhuozhou.jdyc.main.main.adapter.BarterShopAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IndexMenuAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IndexMerchantAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IndexShopAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IndexTabAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IndexTabMenuAdapter;
import com.zhuozhou.jdyc.main.main.adapter.IntegralShopAdapter;
import com.zhuozhou.jdyc.main.main.bean.BasicsTypeBean;
import com.zhuozhou.jdyc.main.main.bean.ChopCommodityTopBean;
import com.zhuozhou.jdyc.main.main.bean.MenuItemBean;
import com.zhuozhou.jdyc.main.main.bean.TabItemBean;
import com.zhuozhou.jdyc.main.main.viewmodel.MainViewModel;
import com.zhuozhou.jdyc.main.settlement.activity.VerificationActivity;
import com.zhuozhou.jdyc.util.apiUtil.DensityUtil;
import com.zhuozhou.jdyc.util.log.LogUtil;
import com.zhuozhou.jdyc.util.selectcity.activities.SelectCityActivity;
import com.zhuozhou.jdyc.wight.recyclerview.FullyGridLayoutManager;
import com.zhuozhou.jdyc.wight.recyclerview.GridSpacingItemDecoration;
import com.zhuozhou.jdyc.wight.recyclerview.MyLayoutManager;
import com.zhuozhou.jdyc.zxing.encode.QRCodeUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * Created by 方舟 on 2017/5/24.
 * 首页
 */

public class IndexFragment extends BaseFragment<MainViewModel, IndexBinding> implements IndexMenuAdapter.OnItemClickListener,
        IndexTabAdapter.OnTabItemClickListener, IndexMerchantAdapter.OnMerchantItemClickListener,
        IndexShopAdapter.OnShopItemClickListener, IndexTabMenuAdapter.OnTabItemMenuClickListener,
        IntegralShopAdapter.OnShopItemClickListener, BarterShopAdapter.OnShopItemClickListener, OnLoadMoreListener {
    private IndexMenuAdapter indexMenuAdapter;
    private IndexTabAdapter indexTabAdapter;
    private IndexTabMenuAdapter indexTabMenuAdapter;
    private IndexMerchantAdapter indexMerchantAdapter;
    private IntegralShopAdapter integralShopAdapter;
    private BarterShopAdapter barterShopAdapter;
    private IndexShopAdapter indexShopAdapter;
    protected SmartRefreshLayout refreshLayout;
    private List<ChopCommodityTopBean> chopCommodityTopBean = new ArrayList<>();
    private int tabItemPage = 1;

    @Override
    public void onResume() {
        super.onResume();
        tabItemPage = 1;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.index;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        if (getActivity() != null && !getActivity().isFinishing()) {
            ((MainActivity) getActivity()).setThemeBarAndToolBarColor(R.color.themeColor);
        }
        refreshLayout = view.findViewById(R.id.smartFreshLayout);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setEnableRefresh(false);
        binding.tvCity.setText(UserAccountHelper.getNewCity());
        binding.tvCity.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), SelectCityActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("city", UserAccountHelper.getNewCity());
            in.putExtras(bundle);
            startActivity(in);
        });
        binding.searchBg.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), SearchActivity.class);
            startActivity(in);
        });
        List<TabItemBean> tabList = new ArrayList<>();
        tabList.add(new TabItemBean("商家", "为你推荐", tabItemType == 0));
        tabList.add(new TabItemBean("聚品", "商品推荐", tabItemType == 1));
        tabList.add(new TabItemBean("兑换", "积分兑换", tabItemType == 2));
        tabList.add(new TabItemBean("易货", "易分商品", tabItemType == 3));
        indexTabAdapter = new IndexTabAdapter(getActivity());
        indexTabAdapter.setList(tabList);
        indexTabAdapter.setOnTabItemClickListener(this);
        binding.mRecyclerViewTab.setAdapter(indexTabAdapter);
        binding.mRecyclerViewTab.setLayoutManager(new FullyGridLayoutManager(getActivity(), 4) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        binding.mRecyclerViewTab.addItemDecoration(new GridSpacingItemDecoration(
                DensityUtil.dp2px(Objects.requireNonNull(getActivity()), 12),
                ContextCompat.getColor(getActivity(), R.color.white)));

        mViewModel.basicsTypeMutableLiveData.observe(this, basicsTypeBean -> {
            List<MenuItemBean> list = new ArrayList<>();
            List<TabItemBean> tabMenuList = new ArrayList<>();
            try {
                for (BasicsTypeBean.ArrayBean.TypeBean type : basicsTypeBean.getArray().getType()) {
                    list.add(new MenuItemBean(type.getImage(), type.getName(), type.getId() + "", ClassifyActivity.class, 30000));
                    tabMenuList.add(new TabItemBean(type.getId(), type.getName(), false));
                }
                indexMenuAdapter = new IndexMenuAdapter(getActivity());
                indexMenuAdapter.setList(list);
                indexMenuAdapter.setViewWidth(binding.mRecyclerViewMenu.getWidth() / 4);
                indexMenuAdapter.setOnItemClickListener(this);
                binding.mRecyclerViewMenu.setAdapter(indexMenuAdapter);
                binding.mRecyclerViewMenu.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2, LinearLayoutManager.HORIZONTAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });

                indexTabMenuAdapter = new IndexTabMenuAdapter(getActivity());
                tabMenuList.get(0).setIsView(true);
                indexTabMenuAdapter.setList(tabMenuList);
                indexTabMenuAdapter.setViewWidth(binding.mRecyclerViewTopMenu.getWidth() / 5);
                indexTabMenuAdapter.setOnTabMenuItemClickListener(this);
                binding.mRecyclerViewTopMenu.setAdapter(indexTabMenuAdapter);
                binding.mRecyclerViewTopMenu.setLayoutManager(new FullyGridLayoutManager(getActivity(), 1, LinearLayoutManager.HORIZONTAL, false) {
                    @Override
                    public boolean canScrollVertically() {
                        return false;
                    }
                });
                List<BannerBean> bannerList = new ArrayList<>();
                for (BasicsTypeBean.ArrayBean.BannerBean type : basicsTypeBean.getArray().getBanner()) {
                    bannerList.add(new BannerBean(type.getImage(), type.getTitle(), type.getContent()));
                }
                binding.indexBannerPicture.setRoundDots(R.drawable.rounded_theme_rect, R.drawable.rounded_default_bg_rect);
                binding.indexBannerPicture.initView(bannerList);
            } catch (Exception e) {

            }
        });
        mViewModel.chopCommodityTopMutableLiveData.observe(this, v -> {
            chopCommodityTopBean = v;
            try {
                for (int i = 0; i < v.size(); i++) {
                    switch (i) {
                        case 0:
                            Glide.with(this)
                                    .load(v.get(0).getImage().get(0))
                                    .into(binding.imageLowPrices);
                            Glide.with(this)
                                    .load(v.get(0).getImage().get(1))
                                    .into(binding.imageSnapUp);
                            break;
                        case 1:
                            Glide.with(this)
                                    .load(v.get(1).getImage().get(0))
                                    .into(binding.imageRecommend);
                            Glide.with(this)
                                    .load(v.get(1).getImage().get(1))
                                    .into(binding.imageRecommend0);
                            binding.tvRecommend.setText(v.get(1).getNumber() + "人推荐");
                            binding.tvRecommend0.setText(v.get(1).getNumber() + "人推荐");
                            break;
                        case 2:
                            Glide.with(this)
                                    .load(v.get(2).getImage().get(0))
                                    .into(binding.imageGood);
                            Glide.with(this)
                                    .load(v.get(2).getImage().get(1))
                                    .into(binding.imageBuy);
                            binding.tvBuy.setText(v.get(1).getNumber() + "人购买");
                            break;
                        case 3:
                            Glide.with(this)
                                    .load(v.get(3).getImage().get(0))
                                    .into(binding.imageCircusee);
                            Glide.with(this)
                                    .load(v.get(3).getImage().get(1))
                                    .into(binding.imageCircusee0);
                            binding.tvCircusee.setText(v.get(3).getNumber() + "人围观");
                            binding.tvCircusee0.setText(v.get(3).getNumber() + "人围观");
                            break;
                    }
                }
            } catch (Exception e) {

            }
        });
        mViewModel.shopIndexMutableLiveData.observe(this, v -> {
            if (tabItemPage > 1 && indexMerchantAdapter != null) {
                if (v.size() == 0) {
                    refreshLayout.finishRefreshWithNoMoreData();
                    binding.tvNoData.setVisibility(View.VISIBLE);
                } else {
                    indexMerchantAdapter.addAll(v);
                    indexMerchantAdapter.notifyDataSetChanged();
                    refreshLayout.finishLoadMore();
                }
            } else if (tabItemType == 0) {
                indexMerchantAdapter = new IndexMerchantAdapter(getActivity());
                indexMerchantAdapter.setList(v);
                indexMerchantAdapter.setOnMerchantItemClickListener(this);
                binding.mRecyclerViewMerchant.setAdapter(indexMerchantAdapter);
                binding.mRecyclerViewMerchant.setLayoutManager(new MyLayoutManager(getActivity()));
            }
        });
        mViewModel.basicsCommodityTypeBeanMutableLiveData.observe(this, v -> {
            switch (tabItemType) {
                case 1:
                    if (tabItemPage > 1 && indexShopAdapter != null) {
                        if (v.getArray().size() == 0) {
                            refreshLayout.finishRefreshWithNoMoreData();
                            binding.tvNoData.setVisibility(View.VISIBLE);
                        } else {
                            indexShopAdapter.addAll(v.getArray());
                            indexShopAdapter.notifyDataSetChanged();
                            refreshLayout.finishLoadMore();
                        }
                    } else {
                        indexShopAdapter = new IndexShopAdapter(getActivity());
                        indexShopAdapter.setList(v.getArray());
                        indexShopAdapter.setOnShopItemClickListener(this);
                        binding.mRecyclerViewShop.setAdapter(indexShopAdapter);
                        binding.mRecyclerViewShop.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2) {
                            @Override
                            public boolean canScrollVertically() {
                                return false;
                            }
                        });
                    }
                    break;
                case 2:
                    if (tabItemPage > 1 && integralShopAdapter != null) {
                        if (v.getArray().size() == 0) {
                            refreshLayout.finishRefreshWithNoMoreData();
                            binding.tvNoData.setVisibility(View.VISIBLE);
                        } else {
                            integralShopAdapter.addAll(v.getArray());
                            integralShopAdapter.notifyDataSetChanged();
                            refreshLayout.finishLoadMore();
                        }
                    } else {
                        integralShopAdapter = new IntegralShopAdapter(getActivity());
                        integralShopAdapter.setList(v.getArray());
                        integralShopAdapter.setOnShopItemClickListener(this);
                        binding.mRecyclerViewShop.setAdapter(integralShopAdapter);
                        binding.mRecyclerViewShop.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2) {
                            @Override
                            public boolean canScrollVertically() {
                                return false;
                            }
                        });
                    }
                    break;
                case 3:
                    if (tabItemPage > 1 && barterShopAdapter != null) {
                        if (v.getArray().size() == 0) {
                            refreshLayout.finishRefreshWithNoMoreData();
                            binding.tvNoData.setVisibility(View.VISIBLE);
                        } else {
                            barterShopAdapter.addAll(v.getArray());
                            barterShopAdapter.notifyDataSetChanged();
                            refreshLayout.finishLoadMore();
                        }
                    } else {
                        barterShopAdapter = new BarterShopAdapter(getActivity());
                        barterShopAdapter.setList(v.getArray());
                        barterShopAdapter.setOnShopItemClickListener(this);
                        binding.mRecyclerViewShop.setAdapter(barterShopAdapter);
                        binding.mRecyclerViewShop.setLayoutManager(new FullyGridLayoutManager(getActivity(), 2) {
                            @Override
                            public boolean canScrollVertically() {
                                return false;
                            }
                        });
                    }
                    break;
            }
        });
        binding.llSale.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), GoodsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", chopCommodityTopBean.get(0).getId());
            bundle.putInt("type", 1);
            bundle.putInt("admin_id", chopCommodityTopBean.get(0).getAdmin_id());
            bundle.putString("name", chopCommodityTopBean.get(0).getName());
            in.putExtras(bundle);
            startActivity(in);
        });
        binding.llGood.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), GoodsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", chopCommodityTopBean.get(1).getId());
            bundle.putInt("type", 1);
            bundle.putInt("admin_id", chopCommodityTopBean.get(1).getAdmin_id());
            bundle.putString("name", chopCommodityTopBean.get(1).getName());
            in.putExtras(bundle);
            startActivity(in);
        });
        binding.llHot.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), GoodsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", chopCommodityTopBean.get(2).getId());
            bundle.putInt("type", 1);
            bundle.putInt("admin_id", chopCommodityTopBean.get(2).getAdmin_id());
            bundle.putString("name", chopCommodityTopBean.get(2).getName());
            in.putExtras(bundle);
            startActivity(in);
        });
        binding.llNew.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), GoodsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("id", chopCommodityTopBean.get(3).getId());
            bundle.putInt("type", 1);
            bundle.putInt("admin_id", chopCommodityTopBean.get(3).getAdmin_id());
            bundle.putString("name", chopCommodityTopBean.get(3).getName());
            in.putExtras(bundle);
            startActivity(in);
        });
        binding.mScrollView.setOnScrollChangeListener((v, scrollX, scrollY, oldScrollX, oldScrollY) -> {
            if (scrollY >= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.VISIBLE);
            }
            if (scrollY <= (binding.mScrollView.getHeight() / 4)) {
                binding.imageTop.setVisibility(View.GONE);
            }
        });

        binding.imageTop.setOnClickListener(v -> {
            binding.mScrollView.fullScroll(View.FOCUS_UP);
        });
        binding.tvVerification.setOnClickListener(v -> {
            Intent in = new Intent(getActivity(), VerificationActivity.class);
            startActivity(in);
        });
    }

    @Override
    protected void initData(Bundle bundle) {
        mViewModel.getBasicsType(UserAccountHelper.getNewCity(), 1, 1);
        mViewModel.getShopIndex(1, false);
        mViewModel.getChopCommodityTop();
    }

    @Override
    public void onItemClick(View view, int position) {
        Intent intent = new Intent(getActivity(), indexMenuAdapter.getList().get(position).getClx());
        Bundle bundle = new Bundle();
        bundle.putInt("id", Integer.parseInt(indexMenuAdapter.getList().get(position).getTag()));
        bundle.putString("name", indexMenuAdapter.getList().get(position).getImageName());
        bundle.putInt("type", 1);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onTabItemMenuClick(TextView view, int position) {
        Intent intent = new Intent(getActivity(), GoodsClassifyActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("id", indexTabMenuAdapter.getList().get(position).getId());
        bundle.putString("name", indexTabMenuAdapter.getList().get(position).getTopName());
        bundle.putInt("type", 1);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ConstantsHelper.QR_CODE:
                if (resultCode == PermissionsActivity.PERMISSIONS_GRANTED) {
                    QRCodeUtil.getInstance().decode(getActivity());
                } else {
                    showToast("相机启动失败");
                }
                break;
        }
    }

    @Override
    public void onTabItemClick(View view, int position) {
        tabItemPage = 1;
        tabItemType = position;
        binding.tvNoData.setVisibility(View.GONE);
        refreshLayout.resetNoMoreData();
        setRecyclerData(position, true);
    }

    public void setRecyclerData(int position, Boolean isShowDialog) {
        LogUtil.show("tabItemPage:" + tabItemPage);
        switch (position) {
            case 0:
                mViewModel.getShopIndex(tabItemPage, isShowDialog);
                break;
            case 1:
                mViewModel.getBasicsCommodityType(isShowDialog,1, tabItemPage);
                break;
            case 2:
                mViewModel.getBasicsCommodityType(isShowDialog,2, tabItemPage);
                break;
            case 3:
                mViewModel.getBasicsCommodityType(isShowDialog,3, tabItemPage);
                break;
        }
        if (position == 0) {
            binding.mRecyclerViewMerchant.setVisibility(View.VISIBLE);
            binding.mRecyclerViewShop.setVisibility(View.GONE);
        } else {
            binding.mRecyclerViewMerchant.setVisibility(View.GONE);
            binding.mRecyclerViewShop.setVisibility(View.VISIBLE);
        }
    }

    private int tabItemType = 0;

    @Override
    public void onMerchantItemClick(View view, int position) {
        Intent in = new Intent(getActivity(), MerchantActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("id", indexMerchantAdapter.getList().get(position).getId() + "");
        in.putExtras(bundle);
        startActivity(in);
    }

    @Override
    public void onShopItemClick(View view, int position) {
        if (tabItemType == 0) return;
        Intent intent = new Intent(getActivity(), GoodsDetailActivity.class);
        Bundle bundle = new Bundle();
        switch (tabItemType) {
            case 1:
                bundle.putString("id", indexShopAdapter.getList().get(position).getCommodity_id() + "");
                break;
            case 2:
                bundle.putString("id", integralShopAdapter.getList().get(position).getCommodity_id() + "");
                break;
            case 3:
                bundle.putString("id", barterShopAdapter.getList().get(position).getCommodity_id() + "");
                break;

        }
        bundle.putInt("type", tabItemType);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        tabItemPage++;
        setRecyclerData(tabItemType, false);
    }
}
